package com.dbumama.market.service.provider;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.dbumama.market.model.AuthUserConfig;
import com.dbumama.market.model.BuyerUser;
import com.dbumama.market.model.Order;
import com.dbumama.market.model.OrderItem;
import com.dbumama.market.model.Product;
import com.dbumama.market.model.PromotionRcd;
import com.dbumama.market.model.SellerReceiver;
import com.dbumama.market.service.api.pay.PayException;
import com.dbumama.market.service.api.pay.PayService;
import com.dbumama.market.service.base.AbstractServiceImpl;
import com.dbumama.market.service.enmu.PaymentStatus;
import com.jfinal.kit.StrKit;
import com.weixin.sdk.api.ApiResult;
import com.weixin.sdk.api.TemplateData;
import com.weixin.sdk.api.TemplateMsgApi;
import com.weixin.sdk.pay.UnifiedOrderApi;
import com.weixin.sdk.pay.UnifiedOrderReqData;
import com.weixin.sdk.pay.UnifiedOrderResData;
import com.weixin.sdk.utils.SignKit;

@Service("payService")
public class PayServiceImpl extends AbstractServiceImpl implements PayService {
	
	public Logger logger = Logger.getLogger(getClass());

	@Override
	public void resultLotteryCallback(BuyerUser paramBuyerUser, TreeMap<String, Object> paramTreeMap)
			throws PayException {
		// TODO Auto-generated method stub

	}

	@Override
	public void resultOrderCallback(BuyerUser user, TreeMap<String, Object> paramTreeMap)
			throws PayException {
		// TODO Auto-generated method stub
	     String tradeNo = (String)paramTreeMap.get("out_trade_no");
	     String transactionId = (String)paramTreeMap.get("transaction_id");
	 

	       List<Order> orders = Order.dao.find("select * from t_order where trade_no = ?", new Object[] { tradeNo });
	       for (Order order : orders) {
	         order.setTransactionId(transactionId);
	         dealOrder(order, user);
	       }
	     

	}

	@Override
	public void resultMemberCardCallback(BuyerUser paramBuyerUser, TreeMap<String, Object> paramTreeMap)
			throws PayException {
		// TODO Auto-generated method stub

	}

	@Override
	public TreeMap<String, Object> prepareToPay(String openId, String tradeNo, BigDecimal payFee, String desc, String ip) throws PayException {
		// TODO Auto-generated method stub
		AuthUserConfig authConfig = (AuthUserConfig)AuthUserConfig.dao.findFirst("select * from t_auth_user_config");
	    
	    String payFee_ = String.valueOf(payFee.multiply(new BigDecimal(100)).intValue());
	    
	    UnifiedOrderResData unifiedOrderResData = null;
	    UnifiedOrderReqData unifiedOrderReqData = null;
	    unifiedOrderReqData = new UnifiedOrderReqData(openId, desc, tradeNo, payFee_, ip, "JSAPI");
	    try
	    {
	      UnifiedOrderApi unifiedOrderApi = new UnifiedOrderApi();
	      unifiedOrderResData = (UnifiedOrderResData)unifiedOrderApi.post(unifiedOrderReqData);
	    }
	    catch (Exception e)
	    {
	      e.printStackTrace();
	      throw new PayException(e.getMessage());
	    }
	    if ((unifiedOrderResData == null) || (!"OK".equals(unifiedOrderResData.getReturn_msg())) ||("FAIL".equals(unifiedOrderResData.getResult_code())))
	    {
	      if (unifiedOrderResData != null) {
	    	 logger.info(unifiedOrderResData.getReturn_msg() + "appId:" + openId + ",secretKey:" + authConfig.getPaySecretKey() + ",mchid:" + authConfig.getPayMchId());
	      }
	      throw new PayException("调用下单接口失败:"+unifiedOrderResData.getReturn_msg());
	    }
	    TreeMap<String, Object> params = new TreeMap();
	    params.put("appId", authConfig.getAppId());
	    params.put("nonceStr", SignKit.genRandomString32());
	    params.put("package", "prepay_id=" + unifiedOrderResData.getPrepay_id());
	    params.put("timeStamp", Long.toString(new Date().getTime()));
	    params.put("signType", "MD5");

	    
	    String paySign = SignKit.sign(params, null);
	    
	    params.put("paySign", paySign);
	    params.put("packageValue", "prepay_id=" + unifiedOrderResData.getPrepay_id());
	    params.put("returnMsg", unifiedOrderResData.getReturn_msg());
	    params.put("sendUrl", "http://kintana.com.cn/pay/result/");
	    params.put("tradeno", tradeNo);
	    logger.info("params:"+params);
	    return params;
	}

	@Override
	public void payByCard(Long paramLong1, Long paramLong2) throws PayException {
		// TODO Auto-generated method stub

	}
	private void dealOrder(Order order, BuyerUser user)
	   {
	     order.setPaymentStatus(Integer.valueOf(PaymentStatus.paid.ordinal()));
	     order.setUpdated(new Date());
	     order.update();
	 
	     List<OrderItem> orderItems = OrderItem.dao.find("select * from t_order_item where order_id=? ", new Object[] { order.getId() });
	 
	     List<Product> products = new ArrayList();
	     for (OrderItem orderItem : orderItems) {
	       Product product = (Product)Product.dao.findById(orderItem.getProductId());
	       products.add(product);
	       product.setStock(Integer.valueOf(product.getStock().intValue() - orderItem.getQuantity().intValue() > 0 ? product.getStock().intValue() - orderItem.getQuantity().intValue() : 0));
	       product.setSales(Long.valueOf(product.getSales().longValue() + orderItem.getQuantity().intValue()));
	       product.update();
	     }
	     
	     List<PromotionRcd> promotionRcds = PromotionRcd.dao.find("select * from t_promotion_rcd where order_id=? ", new Object[] { order.getId() });
	     if(promotionRcds!=null) {
	    	 for(PromotionRcd promotionRcd:promotionRcds) {
	    		 promotionRcd.setUpdated(new Date());
	    		 promotionRcd.setActive(true);
	    		 promotionRcd.update();
	    	 }
	     }

	 
/*		for (Product product : products) {
			ProdCashbackResultDto cashback = this.cashbackService.getProductCashBack(product);
			if (cashback != null) {
				List cashbackRcds = cbrDao.find("select * from t_cashback_rcd where buyer_id=? and product_id=? ",
						new Object[] { user.getId(), product.getId() });
				if ((cashbackRcds == null) || (cashbackRcds.size() >= cashback.getLimit().intValue()))
					break;
				new SendRedpackThread(user, order, orderItems, product, cashback).start();

				break;
			}

		}*/
	 
	     new SendTemplateMsgThread(user, order).start();
	     //new SendPaydTemplateMsgThread(user, order).start();
	   }


	class SendTemplateMsgThread extends Thread {
		private BuyerUser buyerUser;
		private Order order;

		public SendTemplateMsgThread(BuyerUser buyerUser, Order order) {
			this.buyerUser = buyerUser;
			this.order = order;
		}

		public void run() {
			super.run();
			if (this.buyerUser == null)
				return;

			JSONObject json = new JSONObject();
			json.put("template_id_short", "TM00015");
			String templateId = TemplateMsgApi.getTemplateId(json.toString());
			if (StrKit.isBlank(templateId))
				return;

			StringBuffer sbuffer = new StringBuffer();
			List<OrderItem> orderItems = OrderItem.dao.find("select * from t_order_item where order_id=? ",
					new Object[] { this.order.getId() });
			for (OrderItem orderItem : orderItems)
				sbuffer.append(orderItem.getName() + " X " + orderItem.getQuantity());

			if (StrKit.isBlank(templateId))
				return;

			TemplateData templateData = TemplateData.New().setTemplate_id(templateId).setTouser(buyerUser.getOpenId())
					.setUrl("http://kintana.com.cn/order/detail/?orderId=" + order.getId())
					.add("first",  buyerUser.getNickname() + ", 您已完成支付. ", "#173177")
					.add("orderID", order.getOrderSn(), "#173177")
					.add("orderMoneySum", order.getTotalPrice() + ".", "#173177")
					
					.add("orderProductName", sbuffer.toString(), "#173177") 
					 
					.add("remark", "温馨提示：已支付订单将在1小时内配送", "#173177");
			ApiResult apiResult = TemplateMsgApi.send(templateData.build());
			logger.info("templateData:" +templateData.getTemplate_id()+templateData.toString());
			if (!apiResult.isSucceed()) {
				logger.error("error_code:" + apiResult.getErrorCode() + ",error_msg" + apiResult.getErrorMsg());
			}
			
			
			List<SellerReceiver> sellerReceivers = SellerReceiver.dao.find("select * from t_seller_receiver ");
			for (SellerReceiver sellerReceiver : sellerReceivers) {
				
				BuyerUser user = BuyerUser.dao.findFirst("select * from t_buyer_user where open_id=? ", sellerReceiver.getOpenId());

				TemplateData templateData1 = TemplateData.New().setTemplate_id(templateId)
						.setTouser(sellerReceiver.getOpenId())
						.setUrl("http://kintana.com.cn/order/detail/?orderId=" + order.getId())
						.add("first", user.getNickname() + ", 您有1笔新订单, 顾客已付款. ", "#173177")
						.add("orderID", order.getOrderSn(), "#173177")
						.add("orderMoneySum", order.getTotalPrice() + ".", "#173177")

						.add("orderProductName", sbuffer.toString(), "#173177")

						.add("remark", "请您在1小时内配送", "#173177");
				ApiResult apiResult1 = TemplateMsgApi.send(templateData1.build());
				logger.info("templateData:" + templateData1.getTemplate_id() + templateData1.toString());
				if (!apiResult1.isSucceed()) {
					logger.error("error_code:" + apiResult1.getErrorCode() + ",error_msg" + apiResult1.getErrorMsg());
				}
			}
			
		}
	}

	class SendPaydTemplateMsgThread extends Thread {
		private BuyerUser buyerUser;
		private Order order;

		public SendPaydTemplateMsgThread(BuyerUser buyerUser, Order order) {
			this.buyerUser = buyerUser;
			this.order = order;
		}

		public void run() {
			super.run();

			JSONObject json = new JSONObject();
			json.put("template_id_short", "TM00015");
			String templateId = TemplateMsgApi.getTemplateId(json.toString());
			if (StrKit.isBlank(templateId))
				return;

			StringBuffer sbuffer = new StringBuffer();
			List<OrderItem> orderItems = OrderItem.dao.find("select * from t_order_item where order_id=? ",
					new Object[] { this.order.getId() });
			for (OrderItem orderItem : orderItems)
				sbuffer.append(orderItem.getName() + " X " + orderItem.getQuantity());

			if (StrKit.isBlank(templateId))
				return;

			List<SellerReceiver> sellerReceivers = SellerReceiver.dao.find("select * from t_seller_receiver ");
			for (SellerReceiver sellerReceiver : sellerReceivers) {
				BuyerUser user = BuyerUser.dao.findFirst("select * from t_buyer_user where open_id=? ", sellerReceiver.getOpenId());

				TemplateData templateData = TemplateData.New().setTemplate_id(templateId)
						.setTouser(sellerReceiver.getOpenId())
						.setUrl("http://kintana.com.cn/order/detail/?orderId=" + order.getId())
						.add("first", user.getNickname() + ", 您有1笔新订单, 顾客已付款. ", "#173177")
						.add("orderID", order.getOrderSn(), "#173177")
						.add("orderMoneySum", order.getTotalPrice() + ".", "#173177")

						.add("orderProductName", sbuffer.toString(), "#173177")

						.add("remark", "请您在1小时内配送", "#173177");
				ApiResult apiResult = TemplateMsgApi.send(templateData.build());
				logger.info("templateData:" + templateData.getTemplate_id() + templateData.toString());
				if (!apiResult.isSucceed()) {
					logger.error("error_code:" + apiResult.getErrorCode() + ",error_msg" + apiResult.getErrorMsg());
				}
			}
		}
	}
}
		  


